from urllib import parse
import hashlib
import subprocess
import requests
import urllib.parse


class zhihu_v3():
    def __init__(self,url):
        self.url = url  # 相关api

    def call_js_x_s(self, func_name, *args):
        with open(r'ENCRYPT.js', 'r') as f:
            js_code = f.read().strip()
        # 构造要执行的 JS 代码字符串
        js_args = [f"'{arg}'" if isinstance(arg, str) else str(arg) for arg in args]
        js_func_call = f"{func_name}({', '.join(js_args)})"
        js_complete_code = f"{js_code};\nconsole.log({js_func_call});"
        # 使用 Node.js 执行 JS 代码，并将 stdout 存储到 res 变量中
        res = subprocess.run(['node', '-e', js_complete_code], capture_output=True, text=True)
        # 输出函数返回结果
        return res.stdout.strip()

    def get_headers(self):
        host = 'https://www.zhihu.com'
        en_url = urllib.parse.quote(self.url.replace(host, ''), safe='/?~()*!&=.\'')
        f = "+".join(['101_3_3.0', en_url, '"AKCdgpPR0hSPTnWADvuo2iMwzm_RhcN8G-s=|1650525184"'])
        fmd5 = hashlib.new('md5', f.encode()).hexdigest()
        encrypt_str = "2.0_%s" % self.call_js_x_s('D', fmd5)
        headers = {
            'x-app-za': 'OS=Web',
            "x-zse-93": "101_3_3.0",
            "x-zse-96": encrypt_str,
            "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36",
            "Cookie": "cookie"  # 自己的cookie值,
        }
        self.zh_ask(headers)

    def zh_ask(self, headers):
        resp = requests.get(url=self.url, headers=headers)
        print(resp.text)


def start():
    op.get_headers()


if __name__ == '__main__':
    op = zhihu_v3("www.zhihu.com")
    start()